import featureImg1 from '@/assets/img/feature/feature1.png';
import featureImg2 from '@/assets/img/feature/feature2.png';
import featureImg3 from '@/assets/img/feature/feature3.png';

import featureImg4 from '@/assets/img/feature/feature4.png';
import featureImg5 from '@/assets/img/feature/feature5.png';
import featureImg6 from '@/assets/img/feature/feature6.png';
import { ftFocus } from '@/service/modules/home';
import type { ReactNode } from 'react';
import React, { memo, useEffect, useMemo, useState } from 'react';
import './index.less';
import { useNavigate } from 'umi';

interface Iprops {
  children?: ReactNode;
}

// 创建自定义Hook
const useMediaQuery = (query: string): boolean => {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }

    const listener = () => setMatches(media.matches);
    media.addListener(listener);

    return () => media.removeListener(listener);
  }, [matches, query]);

  return matches;
};
const Focus: React.FC<Iprops> = (props) => {
  const navigate = useNavigate();
  const isDesktop = useMediaQuery('(min-width: 768px)');
  const [list, setList1] = useState([]);
  const imgs = [featureImg1, featureImg2, featureImg3, featureImg4, featureImg5, featureImg6];

  // 使用 useMemo 优化性能
  const currentList = useMemo(() => {
    return list.map((item:any, index) => ({
      id: item.id,
      img: imgs[ isDesktop ? index : index + 3],
      title: item.title,
    }));
  }, [isDesktop, list]);

  function onFocus(_item: any) {
    navigate('/docs', { state: { id: _item.id } });
  }
  function cell() {
    return currentList.map((item, index) => (
      <div className="fl-item" key={index} onClick={()=>onFocus(item)}>
        <img src={item.img} alt="" />
        <div className="fti-hocus">
          <div className="ftih-title">{item.title}</div>
        </div>
      </div>
    ));
  }

  useEffect(() => {
    ftFocus().then((res) => {
      console.log(res);
      const { code, data, message } = res;
      if (code === 200) {
        setList1(
          data.map((item: any, index: number) => ({
            id: item.id,
            img: '',
            title: item.title,
          })),
        );
      }
    });
  }, []);

  return (
    <div className="focus">
      <div className="index-title wrapper-v2">聚焦</div>
      <div className="focus-list wrapper-v2">{cell()}</div>
    </div>
  );
};

export default memo(Focus);
